#include <iostream>
using std::cout;
using std::endl;

#include "downloadthread.h"

#include <string>
using std::string;

#include <Poco/Thread.h>
using Poco::Thread;

#include <Poco/Net/StreamSocket.h>
using Poco::Net::StreamSocket;

#include <Poco/FileStream.h>
using Poco::FileOutputStream;

#include <Poco/Net/SocketStream.h>
using Poco::Net::SocketStream;

#include <Poco/StreamCopier.h>
using Poco::StreamCopier;

namespace Commands {

	DownloadThread::DownloadThread(string filename) :
		_server(0),
		_file(filename)
	{
		cout << "DownloadThread :: DownloadThread created" << endl;
	}
	
	UInt16 DownloadThread::port()
	{
		return _server.address().port();
	}

	void DownloadThread::run()
	{
		cout << "DownloadThread :: Waiting for connection " << endl;
		StreamSocket s = _server.acceptConnection();
		cout << "DownloadThread :: Got connection, downloading " << endl;
		FileOutputStream file(_file.path());
		SocketStream is(s);
		int size = StreamCopier::copyStream(is, file);
		cout << "DownloadThread :: Downloaded " << size << "B into '" << _file.path() << "'" << endl;
		s.close();
	}
}
